package com.winspread.ui.fragment

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.core.view.children
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.winspread.ui.R

/**
 *
 * 带tab切换的fragmnet管理  (radiogroup+viewpager)
 *
 *
 * 注意：
 * 1.isRadioButtonbottom 默认false tab在上方  ，设置radioButton_bottom = true  tab在下方viewpager在上方
 * 2.在fragment 中添加此控件 需设置 fmTemp = childFragmentManager
 * 3.fragments 在使用时直接设置LinkedHashMap，radiobutton 的id和fragment 一一对应
 * binding.fragmentBottom.fragments = linkedMapOf(
 *         Pair(R.id.but_1,AFragment()),
 *         Pair(R.id.but_2,AFragment()),
 *         Pair(R.id.but_3,BFragment())
 *

 */
open class TabFragment(context: Context?, attrs: AttributeSet?) :
    LinearLayout(context, attrs) {

    var view: View

    var radio: RadioGroup

    var viewPager: ScrollControlViewPager

    var fmTemp: FragmentManager? = null

    var changeItme: (group: RadioGroup, checkedId: Int) -> Unit = { group, checkedId -> }

    var fragments: LinkedHashMap<Int, Fragment>? = null
        set(value) {
            field = value
            radioChange(radio)
        }


    init {
        val obtainStyledAttributes = context?.obtainStyledAttributes(attrs, R.styleable.FragmentStyle)

        var isRadioButtonBottom = obtainStyledAttributes!!.getBoolean(R.styleable.FragmentStyle_radioButton_bottom, false)

        view = if (isRadioButtonBottom) {
            LayoutInflater.from(context).inflate(R.layout.fragment_bottom, this, true)
        } else {
            LayoutInflater.from(context).inflate(R.layout.fragment_top, this, true)

        }
        radio = view.findViewById(R.id.radio)
        viewPager = view.findViewById(R.id.pager)
        viewPager.isSlide = obtainStyledAttributes!!.getBoolean(R.styleable.FragmentStyle_scroll_control1, true)
        viewPager.isScroll = obtainStyledAttributes!!.getBoolean(R.styleable.FragmentStyle_is_scroll_view, false)


        obtainStyledAttributes?.let {
            radio.setBackgroundColor(
                it.getColor(
                    R.styleable.FragmentStyle_button_color,
                    context.resources.getColor(R.color.white)
                )
            )
        }
        obtainStyledAttributes?.recycle()

    }


    override fun dispatchDraw(canvas: Canvas?) {
        super.dispatchDraw(canvas)
        val children = children
        changeChildView(children)
    }


    /**
     * 调整子view 的位置
     * 当有RadioGroup时候直接吧 RadioGroup放到按钮位置（layout中；自己RadioGroup不显示）
     * 当没有RadioGroup  循环把RadioButton放到自己的RadioGroup中（layout不显示）
     */
    private fun changeChildView(children: Sequence<View>) {
        for (child in children) {
            if (child is RadioGroup) {
                (child.parent as ViewGroup).removeViewInLayout(child)
                (view?.findViewById(R.id.lin_group) as ViewGroup).addView(child)
                radioChange(child)
            } else {
                if (child is RadioButton) {
                    (child.parent as ViewGroup).removeViewInLayout(child)
                    radio.addView(child)
                    changeChildView(children)
                    break
                }
            }
        }
    }


    class MyFragmentPagerAdapter(
        fm: FragmentManager?,
        list: List<Fragment>,
    ) : FragmentPagerAdapter(fm!!, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
        //创建一个List<Fragment>
        private val listFragment: List<Fragment> = list

        override fun getItem(arg0: Int): Fragment {
            return listFragment[arg0] //返回第几个fragment
        }

        override fun getCount(): Int {
            return listFragment.size //总共有多少个fragment
        }

    }

    /**
     * 点击事件
     */
    private fun radioChange(radio: RadioGroup) {
        radio.setOnCheckedChangeListener { group, checkedId ->
            fragments?.keys?.let {
                for ((i, key) in it.withIndex()) {
                    if (checkedId == key) {
                        viewPager.setCurrentItem(i, true)
                    }
                }
            }
            changeItme(group, checkedId)
        }

        var fm: FragmentManager? = null
        fmTemp?.let {
            fm = it
        } ?: let {
            fm = (context as FragmentActivity).supportFragmentManager
        }

        fm?.executePendingTransactions()
        val myFragmentPagerAdapter =
            fragments?.values?.toList()
                ?.let { MyFragmentPagerAdapter(fm, it) } //new myFragmentPagerAdater记得带上两个参数
        viewPager.adapter = myFragmentPagerAdapter
        viewPager.offscreenPageLimit = 3
        viewPager.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionoffsetpixels: Int,
            ) {
            }

            override fun onPageSelected(position: Int) {
                fragments?.keys?.let {
                    for ((i, key) in it.withIndex()) {
                        if (position == i) {
                            radio.findViewById<RadioButton>(key)?.isChecked = true
                        }
                    }
                }
            }
        })


    }

}